<?php
/**
 * @version		$Id:  $
 * @package		Success Framework Mobile
 * @subpackage	Model
 * @copyright	Copyright (C) 2007 - 2010 Success company - VietNam. All rights reserved.
 */
defined('PATH_BASE') or die();
/**
 * Object class, allowing __construct in PHP4.
 *
 * @package		Success.Framework
 * @subpackage	Base
 * @since		1.0
 */
 
class sscls_Model extends sscls_Object 
{
  
  var $_db;
  var $_tables;
  var $_columns;
  
	/**
	 * Constructor
	 *
	 * @since	1.5
	 */
	function __construct()
	{
		$this->_db=ss_Main::getDBO();
        //$this->_tables=new sscls_Tables;
        //$this->_columms=new sscls_Columns;
	}

    /**
    * Executes a sql query. If optional $only_first is set to true, it will
    * return the first row of the result as an array.
    *
    * @param  string  Query to run
    * @param  bool    Return only the first row, as an array?
    * @return mixed
    */
    function query($sql, $only_first = false)
    {
        return $this->_db->query($sql, $only_first = false);
    }
    
    function loadList($i_sql)
    {
   	    return $this->_db->loadList($i_sql);
   	}
    
	/**
	* This global function loads the first row of a query into an object
	*
	* @access	public
	* @return 	object
	*/
	function loadObject($query='' )
	{
	  return $this->_db->loadObject($query);
	}

	/**
	* Load a list of database objects
	*
	* If <var>key</var> is not empty then the returned array is indexed by the value
	* the database key.  Returns <var>null</var> if the query fails.
	*
	* @access	public
	* @param string The field name of a primary key
	* @return array If <var>key</var> is empty as sequential list of returned records.
	*/
	function loadObjectList( $query='' )
	{
	   return $this->_db->loadObjectList($query);
	}
   
    
    /**
	 * This method loads the first field of the first row returned by the query.
	 *
	 * @access	public
	 * @return The value returned in the query or null if the query failed.
	 */
	function loadResult($query='')
	{
		return $this->_db->loadResult($query);
	}
    
    	/**
	 * Load an array of single field results into an array
	 *
	 * @access	public
	 */
	function loadResultArray($query='',$numinarray = 0)
	{
		return $this->_db->loadResultArray($query,$numinarray);
	}

	/**
	* Fetch a result row as an associative array
	*
	* @access	public
	* @return array
	*/
	function loadAssoc($query='')
	{
		return $this->_db->loadAssoc($query);
	}

	/**
	* Load a assoc list of database rows
	*
	* @access	public
	* @param string The field name of a primary key
	* @return array If <var>key</var> is empty as sequential list of returned records.
	*/
	function loadAssocList($query='', $key='' )
	{
		return $this->_db->loadAssocList($query,$key);
	}




    /**
    * Returns the number of queries executed.
    *
    * @param  none
    * @return integer
    */
    function num_queries()
    {
        return $this->_db->num_queries();
    }
    
    
     //save to database by id
    function store($data,$tablename)
    {
        //get list fields in table name
        $fields=$this->_db->getFields($tablename);
        
        //get key in table
        $fleldkey=$this->_db->getKey($tablename);
        
        
    	if(@(int)$data[$fleldkey]!=0)
    	{
    	   //update data to database
            return $this->updateRecord($data,$tablename,$fields,$fleldkey);
    	}
    	else
    	{	
    	   //Insert data to database
            return $this->insertRecord($data,$tablename,$fields,$fleldkey);
    	}
        
    }
    
    //update data to database
    function updateRecord($data,$tablename,$fields,$fleldkey)
    {
                
        foreach($fields as $field)
           {
            if(isset($data[$field]))
				$set[]=$field.'=\''.$data[$field].'\'';
           }
  		
        $sets=(count($set)?' update '.$tablename.' set  '.implode(',',$set): '');
        // where to update
    	$where=' where  '.$fleldkey.' = '.$data[$fleldkey];
        // query update
    	$query=$sets.$where;
        //store to database
		if($this->_db->query($query))
			return true;
		else
			return false;
    }
    
    //Insert data to database
    function insertRecord($data,$tablename,$fields,$fleldkey)
    {
        //get list fields in table name
        $fields=$this->_db->getFields($tablename);
        
        //get key in table
        $fleldkey=$this->_db->getKey($tablename);
        
        //insert new record
        foreach($fields as $field)
        {
            $values[]=@$data[$field];
        }
		$query=(count($fields)?' INSERT INTO '.$tablename.' ('.implode(',',$fields).' ) VALUES (\''.implode('\',\'',$values).'\')':'');
        //store to database
		if($this->_db->query($query))
			return true;
		else
			return false;
    
    }
    
    //get insert id
    function getID()
    {
        return $this->_db->insert_id();
    }
    
    function _getListPaging($rows=array(),$limit=0,$total=0,$option='')
    {
        
        $limitstart_=sscls_Request::getRequest('limitstart');
        $firts=sscls_Request::getRequest('firts');
        $session=ss_Main::getSession();
        if((int)$firts==1)
        {
         $session->set('limitstart.'.$option,$limitstart_);  
        }
        $limitstart=(int)$session->get('limitstart.'.$option);
        $results['value']=$rows;
        $results['pagination']=$this->pagination($limit,$limitstart,$total,$option);
        return $results;
    }
	
	function _getList($query='',$limit=0,$total=0,$option='',$orderby='id')
    {
        
        $limitstart_=sscls_Request::getRequest('limitstart');
        $firts=sscls_Request::getRequest('firts');
        $session=ss_Main::getSession();
        if((int)$firts==1)
        {
         $session->set('limitstart.'.$option,$limitstart_);  
        }
        $limitstart=(int)$session->get('limitstart.'.$option);
        $sql=$query.' LIMIT '.$limitstart.','.$limit;
        $rows=$this->_db->loadObjectList($sql);
        $results['value']=$rows;
        $results['pagination']=$this->pagination($limit,$limitstart,$total,$option);
        return $results;
    }
    
    function pagination($limit,$limitstart,$total,$option)
    {
        $pagination=@(object)$pagination;
        $pagination->total=(int)$total;
        $pagination->limit=(int)$limit;
        $pagination->limitstart=(int)$limitstart;
        $pagination->option=$option;
        $pagination->pagetotal=gettype($total/$limit)=='integer'?$total/$limit:(int)($total/$limit)+1;
        $pagination->pagecurrent=(int)$limitstart/$limit+1;
        return $pagination;        
    }       
    
    //Get object by id
    function getItemById($tablename='',$id=0)
    {      
        $fleldkey=$this->_db->getKey($tablename);          
        return $this->_db->loadObject('select * from '.$tablename.' where '.$fleldkey.'='.(int)$id);
    }
    
    
    
} 
?>